package com.wksc.framework.impexp.thread;

import com.wksc.framework.impexp.constants.IEConstants;
import com.wksc.framework.impexp.constants.TaskStat;
import com.wksc.framework.impexp.log.ImpExpLog;
import com.wksc.framework.impexp.task.Task;
import com.wksc.framework.impexp.util.ClassFactory;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>
 * Title(文件名): ImpExpFuture.java
 * </p>
 * <p>
 * Description(描述): TODO
 * </p>
 * <p>
 * Copyright(版权): Copyright (c) 2011
 * </p>
 * <p>
 * Company(公司): 成都四方信息技术有限公司
 * </p>
 * <p>
 * CreateTime(生成日期)：2011-10-21上午09:28:28
 * </p>
 * 
 * @author wanglei
 * @version impExp_C13
 */
public class ImpExpFuture<BaseResult> extends FutureTask<BaseResult> {

	protected static final ImpExpLog LOG = ClassFactory
			.getLog(ImpExpFuture.class);
	private static final ReentrantReadWriteLock READ_WRITE_LOCK = new ReentrantReadWriteLock();
	private String taskName;

	private Task task;

	public ImpExpFuture(Callable<BaseResult> callable) {
		super(callable);
	}

	public ImpExpFuture(Runnable runnable, BaseResult result) {
		super(runnable, result);
	}

	public void setTaskName(String fileName) {
		this.taskName = fileName;
	}

	public String getTaskName() {
		return taskName;
	}

	public Task getTask() {
		return task;
	}

	public void setTask(Task task) {
		this.task = task;
	}

	@Override
	public boolean cancel(boolean mayInterruptIfRunning) {
		if (mayInterruptIfRunning) {
			task.cancelTask();
			task.setTaskStat(TaskStat.TASK_CANCELLING);
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void done() {
		try {
			TaskManage.writeLock.lock();
			// 结束前从taskList中删除本任务的信息
			TaskManage.delTask(taskName, task.getTaskStat());
			// 清理冲突状态
			TaskManage.clearConflictState(task);
			//以等待队列中的任务个数为循环次数
			int loopTime = TaskManage.getWaitingNum(); //这个地方是将内存waitingQueue中的数据poll出来,所以这个地方以内存为准
			LOG.debug("Job  done: " + taskName);
			if (loopTime > 0) {
				for (int i = 0; i < loopTime; i++) {
					//如果当前运行任务数等于或超过配置的同时执行的线程数,则不再取等待队列中的任务进行添加
					if (TaskManage.getRunningNum() >= IEConstants.THREAD_NUM) {
						break;
					} //这个地方有个bug,加载loopTime是通过查询数据库,但是获得具体任务是通过出栈队列
					Task task = TaskManage.getWaitingQueue().poll();
					if (null != task) {
						TaskManage.addToRun(task);
					}
				} // end for
				//			} else { //如果任务数为0,则自动从数据库中加载,考虑一下是不是写到这个位置
				//不能写到这个位置,因为写到这个位置会造成不断增加的死循环
			} // end if
		} finally {
			TaskManage.writeLock.unlock();
		}
	}
}
